package Tools;

import pyrachnid.model.ground_model.Cell;
import pyrachnid.model.ground_model.Map;
import pyrachnid.model.scenar_model.Scenario;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

/**
 * @author zygou
 *
 */
public class MapConverterXML implements Converter {
	
	private Scenario _scenar;
	
	public MapConverterXML(XStream xstream, Scenario scenar){
		super();
		_scenar = scenar;
		xstream.registerConverter(new CellConverterXML(_scenar));
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public boolean canConvert(Class mapClass) {
		return mapClass.equals(Map.class);
	}

	@Override
	public void marshal(Object mapObject, HierarchicalStreamWriter writer,
			MarshallingContext context) {
		//cast map object
		Map map = (Map)mapObject;
		
		//write atributes
		writer.addAttribute("name", map.getName());
		
		//write nodes
		writer.startNode("dimension");
			writer.addAttribute("x", String.valueOf(map.getXdimension()));
			writer.addAttribute("y", String.valueOf(map.getYdimension()));
		writer.endNode();
		
		writer.startNode("Cells");
			for(Cell[] cells : map.getGround()){
				for(Cell cell : cells){
					context.convertAnother(cell);
				}
			}
		writer.endNode();
	}

	@Override
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
		
		String mapName = reader.getAttribute("name");
		
		reader.moveDown();
			int dimX = Integer.valueOf(reader.getAttribute("x"));
			int dimY = Integer.valueOf(reader.getAttribute("y"));
		reader.moveUp();
		
		_scenar.loadImage(_scenar.getMapPath(), dimX, dimY, mapName);
		
		reader.moveDown();
			while(reader.hasMoreChildren()){
				reader.moveDown();
					context.convertAnother(_scenar.getMap(), Cell.class);
				reader.moveUp();
			}
		reader.moveUp();
		return null;
	}

}
